<template>
  <page-container>
    <search-form
      v-model="searchForm"
      :searchColumns="searchColumns"
      :searchOptions="{ menuSpan: 8 }"
      @on-search="handleSearch">
      <template v-slot:newBtn>
        <el-button
          type="primary"
          @click="allForm('add')"
          >新增影片</el-button
        >
        <el-button @click="batchImport()">批量导入</el-button>
      </template>
    </search-form>

    <avue-table
      :dataList="dataList"
      :loading="loading"
      :page="page"
      :tableColumns="tableColumns"
      :tableOptions="{ menuWidth: 220 }"
      @onPageChange="onPageChange">
      <template v-slot:menu="{ row }">
        <el-button
          type="primary"
          @click="allForm('edit', row)"
          icon="el-icon-edit"
          circle></el-button>
        <el-button
          type="primary"
          @click="detailsChil(row)"
          icon="el-icon-star-off"
          circle></el-button>
        <el-button
          type="primary"
          @click="handleVideo(row)"
          icon="el-icon-video-play"
          circle></el-button>
        <el-button
          type="primary"
          @click="downLoadMp4(row)"
          icon="el-icon-download"
          circle></el-button>
        <el-button
          type="danger"
          @click="delRow(row.id)"
          icon="el-icon-delete"
          circle></el-button>
      </template>
    </avue-table>
    <el-dialog
      :title="`《${videoTitle}》第${episode_no}集`"
      :visible.sync="dialogVisible"
      width="80%"
      height="50%">
      <div id="mse"></div>
    </el-dialog>
    <!-- <XgPlayer
      :dialogVisible="dialogVisible"
      :title="videoTitle"></XgPlayer> -->
  </page-container>
</template>

<script>
import tableMixins from '@/mixins/table'
import { deepClone } from '@/utils'
import { mapGetters } from 'vuex'
import { searchColumns, tableColumns } from './config/table-config'
import { allDialogForm, importDialog } from './config/dialogForm'
import { queryKeyWordForm } from '@/api/sales'
import { getMovieTypeQuery, handleMovieChil } from '@/api/movie'
import { getMovieQuery, addMovieForm, editMovieForm, inportMovies, delMovieForm } from '@/api/movie'
import Player, { Events } from 'xgplayer'
import HlsPlayer from 'xgplayer-hls'
import 'xgplayer/dist/index.min.css'
import XgPlayer from './components/videoDialog.vue'
export default {
  components: { XgPlayer },
  mixins: [tableMixins],
  data() {
    return {
      episode_no: '',
      videoTitle: '',
      dialogVisible: false,
      isAll: true,
      keyWordList: [],
      movieTypeList: [],
      dataList: [],
      childList: [],
      searchForm: {},
      diaForm: {},
      importForm: {
        film_zip: [],
      },
    }
  },
  computed: {
    ...mapGetters(['commonData', 'countryList']),
    userList() {
      return this.commonData?.userList ?? []
    },
    importDialog,
    searchColumns,
    tableColumns,
    allDialogForm,
  },

  methods: {
    fetchMethod: getMovieQuery,
    delMethod: delMovieForm,
    // 查询参数格式化
    formatSearch() {
      const searchParams = deepClone(this.searchForm)
      return searchParams
    },
    downLoadMp4(row) {},
    allForm(type, row) {
      let formData = {}

      formData = deepClone(this.diaForm)
      if (type === 'edit') {
        formData = deepClone(row)
        formData.film_category_id = Number(row?.film_category_id)
        formData.country_id_list = row?.countries?.map(it => it?.id)
        formData.keywords = row?.keywords_name?.map(it => Number(it?.id))
      }
      this.$dialogForm.show({
        title: `${type === 'add' ? '新增' : '编辑'}影片`,
        width: '50%',
        data: formData,
        option: {
          labelWidth: 120,
          column: this.allDialogForm,
        },
        callback: async ({ data, close }) => {
          let resData = {}
          if (type === 'add') {
            data.keywords = data?.keywords.join(',')

            const conutry = this.getCountry(data.country_id_list)
            data.country_id_list = conutry
            resData = await addMovieForm(data)
          } else {
            const parm = {
              ...data,
              release_time: this.$dayjs(data?.release_time).unix(),
              country_id_list: this.getCountry(data?.country_id_list),
              keywords: data?.keywords.join(','),
            }
            delete parm.countries
            delete parm.keywords_name
            resData = await editMovieForm(parm)
          }
          if (resData.code === 0) {
            this.$message.success(`${type === 'add' ? '新增' : '编辑'}成功`)
          }
          close()
          this.getList()
        },
      })
    },
    getCountry(data) {
      const conutry = data
        .filter(item => item)
        .map(it => {
          return {
            id: it === -1 ? -1 : this.countryList.find(item => item.id === it)?.id,
            name: it === -1 ? '所有国家' : this.countryList.find(item => item.id === it)?.full_name,
          }
        })
      return JSON.stringify(conutry)
    },
    detailsChil(row) {
      this.$router.push({
        path: '/film/episodes',
        query: { name: row?.name, id: row?.id, cdn: row?.host },
      })
    },
    async queryKeyWordForm() {
      const { data } = await queryKeyWordForm()
      this.keyWordList = data?.list ?? []
    },
    async getMovieTypeQuery() {
      const { data } = await getMovieTypeQuery()
      let movieTypeArr = data?.list ?? []
      this.movieTypeList = movieTypeArr.map(item => {
        return {
          value: item?.id,
          label: item?.name,
        }
      })
    },
    async handleVideo(row) {
      this.videoTitle = row?.name
      const url = await this.handleMovieChil(row)
      const t_url = url.map(item => item?.url)
      this.dialogVisible = true
      let index = 0

      this.$nextTick(() => {
        const mse = document.querySelector('#mse')
        let config = {
          pip: true,
          el: mse,
          height: '500px',
          width: '100%',
          autoplay: true,
          plugins: [HlsPlayer],
          defaultPlaybackRate: 16,
          playbackRate: [0.5, 0.75, 1, 1.5, 2, 6, 10, 16], //倍速
          url: t_url[index],
        }
        const player = new Player(config)

        this.episode_no = url[index]?.episode_no
        let id = row?.id
        player.on('ended', () => {
          if (index <= t_url.length - 1) {
            this.episode_no = url[index]?.episode_no
            index++
            player.playNext({ url: t_url[index], autoplay: true })
          } else {
            this.episode_no = url[index]?.episode_no
            this.$message({
              showClose: true,
              message: `影片ID: ${row?.id} 影片:《${row?.name}》自测完成`,
              type: 'success',
              duration: 0,
            })
          }
        })
        player.on('error', row => {
          this.$message({
            showClose: true,
            message: `影片ID: ${id}
            error：${row?.message}
            url：${row?.url}`,
            type: 'error',
            duration: 0,
          })
        })
      })
    },

    async handleMovieChil(row) {
      const { data } = await handleMovieChil({ film_id: row?.id, page: 1, page_size: 100 })
      const movie_list = data?.list ?? []
      const urlArr = movie_list?.map(item => {
        return {
          id: item?.id,
          episode_no: item?.episode_no,
          url: `${row?.host}/${item?.url.find(it => it?.indexOf('m3u8') != -1)}`,
        }
      })
      return urlArr
    },

    batchImport() {
      const parm = this.importForm
      parm.film_zip = []
      this.$dialogForm.show({
        title: '批量导入',
        width: '30%',
        data: parm,
        option: {
          column: this.importDialog,
        },
        callback: async ({ data, close }) => {
          const parms = data?.film_zip.map(item => item?.url).join(',')
          const resData = await inportMovies(parms)
          if (resData.code === 0) {
            this.$message.success('导入成功')
          }
          this.getList()
          close()
        },
      })
    },
  },

  mounted() {
    this.handleSearch()
    this.queryKeyWordForm()
    this.getMovieTypeQuery()
  },
}
</script>

<style lang="scss" scoped></style>
